// File Name: oled_logic.c
// Author: kukukukuku~
// Date: 2024-10-25

#include "./OLED/inc/oled_font.h"
#include "./OLED/inc/oled_logic.h"

/**
 * @brief   OLED设置坐标
 * @param   x:  横坐标
 * @param   y:  纵坐标
 * @retval  None
 * @note    None
*/
void oled_set_position(const uint8_t x, const uint8_t y)
{
    if(x > OLED_COLUMN_MAX - 8 || y > OLED_PAGE_MAX - 1)
        return;
    
    oled_send_data(0xB0 + y, OLED_SEND_CMD);
    oled_send_data((x & 0xF0) >> 4 | 0x10, OLED_SEND_CMD);
    oled_send_data(x & 0x0F, OLED_SEND_CMD);
}


/**
 * @brief   OLED开启
 * @param   None
 * @retval  None
 * @note    None
*/
void oled_on(void)
{
    oled_send_data(0x8D, OLED_SEND_CMD);
    oled_send_data(0x14, OLED_SEND_CMD);
    oled_send_data(0xAF, OLED_SEND_CMD);
}


/**
 * @brief   OLED关闭
 * @param   None
 * @retval  None
 * @note    None
*/
void oled_off(void)
{
    oled_send_data(0x8D, OLED_SEND_CMD);
    oled_send_data(0x10, OLED_SEND_CMD);
    oled_send_data(0xAE, OLED_SEND_CMD);
}


/**
 * @brief   OLED清屏
 * @param   None
 * @retval  None
 * @note    None
*/
void oled_clear(void)
{
    for(uint8_t i = 0; i < OLED_PAGE_MAX; i++)
    {
        oled_send_data(0xB0 + i, OLED_SEND_CMD);
        oled_send_data(0x00, OLED_SEND_CMD);
        oled_send_data(0x10, OLED_SEND_CMD);
        
        for(uint8_t j = 0; j < OLED_COLUMN_MAX; j++)
            oled_send_data(0x00, OLED_SEND_DATA);
    }
}


/**
 * @brief   OLED显示一个8x16字符
 * @param   x:          横坐标
 * @param   y:          纵坐标
 * @param   ch:         要显示的字符
 * @param   mode:       显示模式
 *                      @arg 0: 正相
 *                      @arg 1: 反相
 * @retval  None
 * @note    None
*/
void oled_show_char_8x16(const uint8_t x, const uint8_t y, const uint8_t ch, const uint8_t mode)
{
    uint8_t data = 0;
    
    if(x > OLED_COLUMN_MAX - 8 || y > OLED_PAGE_MAX - 2 || ch > 127)
        return;
    
    //一个字符占2页
    for(uint8_t i  = 0; i < 2; i++)
    {
        oled_set_position(x, y + i);
        
        //一个字符在每页占8列
        for(uint8_t j = 0; j < 8; j++)
        {
            data = oledFont8x16[ch * 16 + 8 * i + j];
            oled_send_data(mode ? ~data : data, OLED_SEND_DATA);
        }
    }
}


/**
 * @brief   OLED显示8x16字符串
 * @param   x:          横坐标
 * @param   y:          纵坐标
 * @param   str:        要显示的字符串
 * @param   mode:       显示模式
 *                      @arg 0: 正相
 *                      @arg 1: 反相
 * @retval  None
 * @note    None
*/
void oled_show_str_8x16(const uint8_t x, const uint8_t y, const uint8_t * const str, const uint8_t mode)
{
    uint8_t xx = x, yy = y;
    uint8_t i = 0;
    
    if(x > OLED_COLUMN_MAX - 8 || y > OLED_PAGE_MAX - 2 || str == NULL)
        return;
    
    while(str[i])
    {
        if(xx > OLED_COLUMN_MAX - 8)
        {
            xx = 0;
            yy += 2;
        }
        
        if(yy > OLED_PAGE_MAX - 2)
            return;
        
        oled_show_char_8x16(xx, yy, str[i++], mode);
        
        xx += 8;
    }
}
